<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="单元划分管理"
      titleHelpMessage="划分单元的颗粒度、用途；划分单元的目的是便于安全风险评估工作的全面开展，避免出现遗漏。单元可以理解为独立的场所（区域）、设备设施装置（部位）、作业活动等。"
      :indentSize="30"
      :pagination="false"
      :searchInfo="searchInfo"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
      @fetch-success="onFetchSuccess"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddUnitDivisionButtonClick">新增</a-button>
      </template>
      <template #unitname="{ column, record }">
        <a @click="onViewUnitDivisionButtonClick(record)">{{ record.unitname }}</a>
      </template>
      <template #uccd="{ column, record }">
        {{ returnCategoryName(record.uccd, unitCategoryData) }}
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditUnitDivisionButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteUnitDivisionButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:eye-outlined',
              label: '查看',
              onClick: onViewUnitDivisionButtonClick.bind(null, record),
            },
            {
              label: '静态信息维护',
              color: 'success',
              onClick: onEditStaticInfoButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddOrUpdateUnitDivision
      @register="registerAddOrUpdateUnitDivisionModal"
      @success="afterSuccess"
    />
    <UnitBasicInfoDrawer @register="registerUnitBasicInfo" @success="afterSuccess" />
    <UnitStaticInfoModal @register="registerUnitStaticInfo" @success="afterSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref, nextTick, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryUnitDivision, deleteUnitDivision } from '/@/api/ehs/unitDivision';
  import { EhsUnitTreeTableItemDto } from '/@/api/ehs/model/unitDivisionModel';
  import { getOrgDeptList, getUserOrganization } from '/@/api/ehs/organization';
  import { useDrawer } from '/@/components/Drawer';
  import { unitDivisionTableColumns, queryUnitConditionFormSchema } from './unitDivision.data';
  import { queryUnitCategory } from '/@/api/ehs/unitCategory';
  import AddOrUpdateUnitDivision from './AddOrUpdateUnitDivision.vue';
  import UnitBasicInfoDrawer from './UnitBasicInfoDrawer.vue';
  import UnitStaticInfoModal from './UnitStaticInfoModal.vue';
  export default defineComponent({
    name: 'unitDivisionIndex',
    components: {
      BasicTable,
      TableAction,
      AddOrUpdateUnitDivision,
      UnitBasicInfoDrawer,
      UnitStaticInfoModal,
    },
    setup() {
      const orgcode = ref('');
      const [registerAddOrUpdateUnitDivisionModal, { openModal: openAddOrUpdateUnitDivision }] =
        useModal();
      const [registerUnitStaticInfo, { openModal: openEditUnitStaticInfo }] = useModal();
      const [registerUnitBasicInfo, { openDrawer: openUnitBasicInfoDrawwer }] = useDrawer();
      const deptData = ref([]);
      const unitCategoryData = ref([]);
      const searchInfo = ref({
        includechilds: true,
        isdept: false,
      });
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const [registerTable, { reload, getDataSource, getForm, expandAll }] = useTable({
        api: queryUnitDivision,
        columns: unitDivisionTableColumns,
        canResize: true,
        striped: false,
        showTableSetting: true,
        showIndexColumn: false,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        useSearchForm: true,
        formConfig: {
          labelWidth: 80,
          schemas: queryUnitConditionFormSchema,
          showResetButton: false,
        },
        immediate: false,
        beforeFetch: (params) => {
          return {
            ...params,
            flagisvalid: false,
            orgcode: orgcode.value,
          };
        },
        afterFetch: (data) => {
          return data ?? [];
        },
        actionColumn: {
          width: 320,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }
      /**
       * 打开新增窗口
       */

      function onAddUnitDivisionButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '单元管理',
          operateType: OperationTypeEnum.ADD,
        };
        openAddOrUpdateUnitDivision(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditUnitDivisionButtonClick(record: EhsUnitTreeTableItemDto) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '单元管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.unitid,
        };
        openAddOrUpdateUnitDivision(true, propsData);
      }
      /**
       * 查看基础信息
       */
      function onViewUnitDivisionButtonClick(record: EhsUnitTreeTableItemDto) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '单元基础信息',
          operateType: OperationTypeEnum.VIEW,
          dataId: record.unitid,
        };
        openUnitBasicInfoDrawwer(true, propsData);
      }

      /**
       * 静态信息维护
       */
      function onEditStaticInfoButtonClick(record: EhsUnitTreeTableItemDto) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: record.unitname,
          operateString: '静态信息维护',
          dataId: record.unitid,
        };
        openEditUnitStaticInfo(true, propsData);
      }

      /**
       * 删除
       * @param record
       */
      function onDeleteUnitDivisionButtonClick(record: EhsUnitTreeTableItemDto) {
        deleteUnitDivision(record.unitid)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
          });
      }

      function onFetchSuccess() {
        nextTick(expandAll);
      }

      function returnCategoryName(uccd, unitCategory) {
        for (let i = 0; i < unitCategory.length; i++) {
          let a = unitCategory[i];
          if (a.uccd == uccd) {
            return a.ucnm;
          } else {
            if (a.children && a.children.length > 0) {
              let res = returnCategoryName(uccd, a.children);
              if (res) {
                return res;
              }
            }
          }
        }
        return uccd;
      }
      onMounted(() => {
        //  获取枚举类
        queryUnitCategory()
          .then((res) => {
            unitCategoryData.value = res;
            getForm().updateSchema({
              field: 'uccd',
              componentProps: {
                treeData: res,
                fieldNames: { label: 'ucnm', value: 'uccd', children: 'children' },
              },
            });
          })
          .catch((e) => {});
        getUserOrganization(projectCode.value).then((res) => {
          orgcode.value = res.orgcode;
          reload();
          getOrgDeptList(res.orgcode)
            .then((res) => {
              if (res) {
                deptData.value = res.map((item) => {
                  return {
                    label: item.name,
                    value: Number(item.id),
                  };
                });
              }
            })
            .catch((e) => {});
        });
      });

      return {
        searchInfo,
        deptData,
        unitCategoryData,
        onFetchSuccess,
        registerUnitBasicInfo,
        registerAddOrUpdateUnitDivisionModal,
        registerUnitStaticInfo,
        registerTable,
        afterSuccess,
        onAddUnitDivisionButtonClick,
        onEditUnitDivisionButtonClick,
        onDeleteUnitDivisionButtonClick,
        onViewUnitDivisionButtonClick,
        returnCategoryName,
        onEditStaticInfoButtonClick,
      };
    },
  });
</script>

<style scoped>
  a {
    color: #000000;
  }
</style>
